package com.zy.mydemo.common.config;

import com.zy.mydemo.api.service.UserService;
import com.zy.mydemo.common.entity.UserEntity;
import com.zy.mydemo.common.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


/**
 * @Author:zhongyong
 * @Description：
 * @Date：Create in 2020/04/30
 */
public class ShiroRealm extends AuthorizingRealm {

    @Resource
    UserService userService;

    /**
     * 授权逻辑
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //这里就获取到user了
        UserEntity user = (UserEntity) principalCollection.getPrimaryPrincipal();
        //这样也可以获取到
//        Subject subject = SecurityUtils.getSubject();
//        UserEntity user = (UserEntity)subject.getPrincipal();

        authorizationInfo.addStringPermission("user:get");

        return authorizationInfo;
    }

    /**
     * 执行认真逻辑
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证程序1");

        if (authenticationToken == null) {
            return null;
        }

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String loginId = token.getUsername();

        if (StringUtils.isEmpty(loginId)) {
            return null;
        }

        UserEntity user = userService.findUser(new UserEntity(){{
            setLoginId(loginId);
        }});

        if (user == null) {
            return null;
        }

        ByteSource salt = null;
        if (user.getSalt() != null) {
            salt = new SimpleByteSource(user.getSalt());
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());
    }
}
